package com.otp.service.impl;

import com.otp.exception.BusinessException;
import com.otp.pojo.entity.Paper;
import com.otp.pojo.entity.PaperSubmission;
import com.otp.pojo.entity.Question;
import com.otp.pojo.request.paper.*;
import com.otp.repository.PaperRepository;
import com.otp.repository.PaperSubmissionRepository;
import com.otp.repository.QuestionRepository;
import com.otp.service.PaperService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

@Service
public class PaperServiceImpl implements PaperService {
    @Autowired
    private PaperRepository paperRepository;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private PaperSubmissionRepository paperSubmissionRepository;

    @Override
    public List<Paper> list() {
        return paperRepository.findAll();
    }

    @Override
    public List<Paper> listByStatus(String status) {
        return paperRepository.findByStatus(status);
    }

    @Override
    public Paper getById(Long id) {
        return paperRepository.findById(id)
                .orElseThrow(() -> new BusinessException("试卷不存在"));
    }

    @Override
    public Paper create(PaperCreateRequest request) {
        // 验证试题是否存在
        validateQuestionIds(request.getQuestionIds());
        Paper paper = new Paper();
        BeanUtils.copyProperties(request, paper);
        paper.setStatus("DRAFT");
        return paperRepository.save(paper);
    }

    @Override
    public Paper update(PaperUpdateRequest request) {
        Paper paper = paperRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("试卷不存在"));
        // 验证试题是否存在
        validateQuestionIds(request.getQuestionIds());
        BeanUtils.copyProperties(request, paper);
        return paperRepository.save(paper);
    }

    @Override
    public Paper publish(Long id) {
        Paper paper = paperRepository.findById(id)
                .orElseThrow(() -> new BusinessException("试卷不存在"));
        if ("PUBLISHED".equals(paper.getStatus())) {
            throw new BusinessException("试卷已发布");
        }
        // 验证试题是否存在
        validateQuestionIds(paper.getQuestionIds());
        paper.setStatus("PUBLISHED");
        return paperRepository.save(paper);
    }

    @Override
    public void delete(Long id) {
        Paper paper = paperRepository.findById(id)
                .orElseThrow(() -> new BusinessException("试卷不存在"));
        paperRepository.delete(paper);
    }

    @Override
    public PaperSubmission submit(PaperSubmissionRequest request) {
        Paper paper = paperRepository.findById(request.getPaperId())
                .orElseThrow(() -> new BusinessException("试卷不存在"));

        if (!"PUBLISHED".equals(paper.getStatus())) {
            throw new BusinessException("试卷未发布，无法提交");
        }

        // 验证答案中的试题 ID 是否属于该试卷
        if (!new HashSet<>(paper.getQuestionIds()).containsAll(request.getAnswers().keySet())) {
            throw new BusinessException("提交的答案包含无效试题 ID");
        }

        PaperSubmission submission = new PaperSubmission();
        submission.setPaperId(request.getPaperId());
        submission.setStudentId(request.getStudentId());
        submission.setAnswers(request.getAnswers());
        submission.setStatus("SUBMITTED");
        return paperSubmissionRepository.save(submission);
    }

    private void validateQuestionIds(List<Long> questionIds) {
        if (questionIds == null || questionIds.isEmpty()) {
            throw new BusinessException("试卷必须包含至少一个试题");
        }
        List<Long> invalidIds = questionIds.stream()
                .filter(id -> !questionRepository.existsById(id))
                .toList();
        if (!invalidIds.isEmpty()) {
            throw new BusinessException("以下试题 ID 不存在: " + invalidIds);
        }
    }
}